package com.shuai.AI.demo.invoke; // 建议dashscope SDK的版本 >= 2.12.0

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.shuai.AI.demo.constants.CommonsUtil;
import java.util.Arrays;

public class SdkAiInvoke {
  public static GenerationResult callWithMessage()
      throws ApiException, NoApiKeyException, InputRequiredException {
    Generation gen = new Generation();
    Message systemMsg =
        Message.builder()
            .role(Role.SYSTEM.getValue())
            // 给ai大模型进行系统预设角色
            .content("你是一个java架构师，精通Java编程")
            .build();
    Message userMsg =
        Message.builder()
            .role(Role.USER.getValue())
            .content("我有一个问题，redis的数据结构底层原理？以及redis的分布式锁，红锁是什么？它解决了什么实际开发问题")
            .build();
    GenerationParam param =
        GenerationParam.builder()
            // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
            //            .apiKey(System.getenv(CommonsUtil.API_KEY))
            .apiKey(CommonsUtil.API_KEY)
            // 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
            .model("qwen-plus")
            .messages(Arrays.asList(systemMsg, userMsg))
            .resultFormat(GenerationParam.ResultFormat.MESSAGE)
            .build();
    return gen.call(param);
  }

  public static void main(String[] args) {
    try {
      GenerationResult result = callWithMessage();
      System.out.println(JsonUtils.toJson(result));
    } catch (ApiException | NoApiKeyException | InputRequiredException e) {
      // 使用日志框架记录异常信息
      System.err.println(
          "An error occurred while calling the generation service: " + e.getMessage());
    }
    System.exit(0);
  }
}
